package com.xxwu.springlibrary.interceptor;

import com.xxwu.springlibrary.contans.Contans;
import com.xxwu.springlibrary.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final HttpSession httpSession;

    public LoginInterceptor(HttpSession httpSession) {
        this.httpSession = httpSession;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("目标方法执行前执行 LoginInterceptor.preHandle...");
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Contans.USER_SESSION_KEY);
        log.info("userInfo{} 用户信息:" + userInfo);
        if(userInfo == null) {
            response.setStatus(401);
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("目标方法执行后执行 LoginInterceptor.postHandle...");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("结果视图渲染 LoginInterceptor.afterCompletion...");
    }
}
